package com.gk.study.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gk.study.entity.Course;
import com.gk.study.entity.Homework;
import com.gk.study.entity.Thing;
import com.gk.study.mapper.CourseMapper;
import com.gk.study.mapper.HomeworkMapper;
import com.gk.study.service.HomeworkService;
import com.gk.study.service.ThingService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class HomeworkServiceImpl extends ServiceImpl<HomeworkMapper, Homework> implements HomeworkService {

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    ThingService thingService;

    @Value("${File.uploadPath}")
    private String uploadPath;

    @Override
    public List<Homework> getHomeworkByTeacher(Long teacherId) {
        return baseMapper.selectByTeacherId(teacherId);
    }

    @Override
    public void publishHomework(Homework homework, MultipartFile file) throws Exception {
        // 验证课程是否属于该教师且状态为PROGRESS
        Course course = courseMapper.selectById(homework.getCourseId());
        if (course == null || !course.getTeacherId().equals(homework.getTeacherId())) {
            throw new RuntimeException("课程不存在或无权操作");
        }
        if (!course.getStatus().name().equals("PROGRESS")) {
            throw new RuntimeException("只能给进行中的课程发布作业");
        }

        // 查询课程关联的学生列表
        List<Long> studentIds = courseMapper.selectStudentIdsByCourseId(course.getId());
        if (studentIds.isEmpty()) {
            throw new RuntimeException("课程未关联学生");
        }

        // 处理附件上传
        String attachmentFileName = null;
        if (file != null && !file.isEmpty()) {
            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            String savePath = uploadPath + "/attachment/" + fileName;
            file.transferTo(new File(savePath));
            attachmentFileName = fileName;
        }

        if (file != null && !file.isEmpty()) {
            System.out.println("接收到文件：" + file.getOriginalFilename() + "，大小：" + file.getSize());

            File uploadDir = new File(uploadPath + "/attachment/");
            if (!uploadDir.exists()) {
                if (!uploadDir.mkdirs()) {
                    throw new IOException("无法创建上传目录");
                }
            }
        }

        Thing teacher = thingService.getById(homework.getTeacherId());
        String teacherName = teacher.getTitle(); // 关键修改：使用 getTitle()

        // 获取课程标题
        String courseTitle = course.getTitle();

        // 为每个学生创建作业记录
        for (Long studentId : studentIds) {
            Homework studentHomework = new Homework();
            BeanUtils.copyProperties(homework, studentHomework);
            studentHomework.setStudentId(studentId);
            studentHomework.setCourseTitle(course.getTitle()); // 设置课程标题
            studentHomework.setTeacherName(teacherName);       // 关键：设置教师名称
            studentHomework.setCourseTitle(courseTitle); // 关键：设置课程标题
            studentHomework.setAttachment(attachmentFileName);
            studentHomework.setPublishTime(LocalDateTime.now());
            this.save(studentHomework);
        }
    }

    @Override
    public void submitHomework(Long homeworkId, String answer, MultipartFile file) throws IOException {
        Homework homework = this.getById(homeworkId);
        if(homework == null) throw new RuntimeException("作业不存在");


        if(file != null && !file.isEmpty()){
            String fileName = "student_" + System.currentTimeMillis() + "_" + file.getOriginalFilename();
            String savePath = uploadPath + "/attachment/" + fileName;
            file.transferTo(new File(savePath));
            homework.setStudentAttachment(fileName);
        }

        homework.setStudentAnswer(answer);
        homework.setStatus(1);
        this.updateById(homework);
    }

    @Override
    public void correctHomework(Long homeworkId, Double score) {
        Homework homework = this.getById(homeworkId);
        if(homework == null) throw new RuntimeException("作业不存在");

        if(score < 0 || score > 100) throw new RuntimeException("分数不合法");

        homework.setScore(score);
        homework.setStatus(2);
        this.updateById(homework);
    }

    @Override
    public List<Homework> getPublishedHomeworkWithCourse(Long teacherId) {
        List<Homework> homeworkList = baseMapper.selectByTeacherId(teacherId);

        // 补充课程封面信息
        homeworkList.forEach(homework -> {
            Course course = courseMapper.selectById(homework.getCourseId());
            if(course != null) {
                homework.setCourseCover(course.getCover());
            }
        });

        return homeworkList;
    }

    @Override
    public List<Homework> getHomeworkByStudentAndStatus(Long studentId, Integer status) {
        LambdaQueryWrapper<Homework> query = new LambdaQueryWrapper<>();
        query.eq(Homework::getStudentId, studentId)
                .eq(status != null, Homework::getStatus, status)
                .orderByDesc(Homework::getDeadline);
        return this.list(query);
    }


    @Override
    public List<Homework> getStudentScores(Long studentId, String courseTitle) {
        LambdaQueryWrapper<Homework> query = new LambdaQueryWrapper<>();
        query.eq(Homework::getStudentId, studentId)
                .eq(Homework::getStatus, 2) // 已批改
                .isNotNull(Homework::getScore)
                .orderByDesc(Homework::getPublishTime);
        if (StringUtils.isNotBlank(courseTitle)) {
            query.eq(Homework::getCourseTitle, courseTitle);
        }
        query.last("LIMIT 10"); // 限制最新10条
        return this.list(query);
    }

    @Override
    public List<String> getStudentCoursesWithScores(Long studentId) {
        LambdaQueryWrapper<Homework> query = new LambdaQueryWrapper<>();
        query.select(Homework::getCourseTitle)
                .eq(Homework::getStudentId, studentId)
                .eq(Homework::getStatus, 2)
                .isNotNull(Homework::getScore)
                .groupBy(Homework::getCourseTitle);
        return this.list(query)
                .stream()
                .map(Homework::getCourseTitle)
                .distinct()
                .collect(Collectors.toList());
    }



    @Override
    public List<Long> getTeachingStudents(String teacherUserId) {
        // 1. 根据user_id获取教师信息
        Thing teacher = thingService.getThingByUserId(teacherUserId);
        if (teacher == null) throw new RuntimeException("教师信息不存在");

        // 2. 查询该教师所有关联学生
        return baseMapper.selectStudentsByTeacher(teacher.getId());
    }

    @Override
    public Map<String, List<Map<String, Object>>> getTeachingAnalysisData(String teacherUserId, Long studentId) {
        // 1. 获取教师ID
        Thing teacher = thingService.getThingByUserId(teacherUserId);
        if (teacher == null) throw new RuntimeException("教师信息不存在");

        // 2. 构建查询条件
        LambdaQueryWrapper<Homework> query = new LambdaQueryWrapper<>();
        query.select(Homework::getStudentId, Homework::getScore, Homework::getPublishTime)
                .eq(Homework::getTeacherId, teacher.getId())
                .eq(Homework::getStatus, 2)
                .isNotNull(Homework::getScore)
                .apply("publish_time >= DATE_SUB(NOW(), INTERVAL 10 DAY)") // 最近10天
                .orderByAsc(Homework::getPublishTime);

        if (studentId != null) {
            query.eq(Homework::getStudentId, studentId);
        }

        // 3. 执行查询并处理数据
        List<Homework> records = this.list(query);

        // 4. 按学生分组数据
        Map<Long, List<Map<String, Object>>> result = new HashMap<>();

        records.forEach(hw -> {
            Map<String, Object> dataPoint = new HashMap<>();
            dataPoint.put("score", hw.getScore());
            dataPoint.put("time", hw.getPublishTime());

            result.computeIfAbsent(hw.getStudentId(), k -> new ArrayList<>())
                    .add(dataPoint);
        });

        // 转换为前端需要的格式
        Map<String, List<Map<String, Object>>> finalResult = new HashMap<>();
        result.forEach((sId, data) -> {
            finalResult.put("student_" + sId, data);
        });

        return finalResult;
    }
}